import { getTemplate, getSlotTemplate, getStringTypeAttr } from '@/components/template'
import guid from '@/utils/guid'
import { RadioGroup } from '@/components/data'
// 深度合并
function Long(name){
    this.name = name
}
function _New(fn,name){
    let obj = {}
    Object.setPrototypeOf(obj,fn)
    let a = fn.call(obj,name)
    return a.instanceof(Object) ? a : obj
}
import mergeDeep from '@/utils/mergeDeep'
var handle = function (_attr, _slots, { id }, slotTag) {
  console.log('父组件拿到子组件的属性，准备渲染=====',slotTag)
  
  //定义默认属性
  let attributes = RadioGroup,
    slots = {
      default: [],
    }

  //覆盖默认属性
  Object.assign(slots, _slots)
  Object.assign(attributes, _attr)
  if (attributes.itemNum.value < 0 || !attributes.itemNum.value) attributes.itemNum.value = 0

  //根据组件不同需要做的不同操作
  let max = _attr.itemNum ? _attr.itemNum.value : attributes.itemNum.value
  let components = JSON.parse(JSON.stringify(_Vue.$store.state.components))
  let component = components.find((c) => c.info.id === id) || { slots }
  let oldSlots = component.slots
  let defaul = [] //default
  
  let addComponent = (_attr, _slots) => {
    let info = {
      name: 'Radio',
      ui: 'iview-UI',
      id: guid(),
    }
    let colComponent = getTemplate(info, _attr, _slots)
    colComponent.parentId = id
    components.push(colComponent)
    return colComponent
  }
  for (let i = 0; i < max; i++) {
    if (oldSlots.default[i]) {
      defaul.push(oldSlots.default[i])
    } else {
      defaul.push({ id: addComponent().info.id })
    }
  }

  //quantity数值减少时，子属性要对应的删除
  let arr = oldSlots.default.filter((item) => {
    //得到所有要删除的对象
    return defaul.findIndex(({ id }) => id === item.id) === -1
  })
  arr.forEach(({ id }) => {
    let index = components.findIndex((c) => c.info.id === id)
    components.splice(index, 1)
  })
  slots.default = defaul
  _Vue.$store.commit('setState', { components: components })

  //获取插槽模板内容
  // 这里当渲染完成后，再修改样式，此时slotTag就是空置了
  let subContent = getSlotTemplate(slots, slotTag)

  //设置当前组件的slot
  
  if (attributes.slot && attributes.slot !== 'default') {
    attributes.slot = {
      type: 'text',
      value: attributes.slot,
    }
  } else {
    attributes.slot = {
      type: 'text',
      value: '',
    }
  }

  //字符串模板操作
  let stringAttr = getStringTypeAttr(attributes)
  
  let template = `<Radio-group
                        ${stringAttr}>
                        ${subContent}
                    </Radio-group>`

  //删除自定义非ui属性
  template = template.replace(`:itemNum="${attributes.itemNum.value}"`, '')
  
  return { template, attributes, slots }
}
export default handle
